package me.flyray.crm.core.biz.merchant;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.flyray.common.msg.ResponseCode;
import me.flyray.crm.core.biz.platform.PlatformBaseBiz;
import me.flyray.crm.core.client.FeignAdminClient;
import me.flyray.crm.core.entity.CustomerBase;
import me.flyray.crm.core.entity.MerchantBase;
import me.flyray.crm.core.entity.MerchantBaseExt;
import me.flyray.crm.core.mapper.CustomerBaseMapper;
import me.flyray.crm.core.mapper.MerchantBaseExtMapper;
import me.flyray.crm.core.mapper.MerchantBaseMapper;
import me.flyray.crm.facade.request.MerchantBaseRequest;
import me.flyray.crm.facade.request.QueryMerchantBaseListRequest;
import me.flyray.crm.facade.request.QueryMerchantListParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.flyray.common.biz.BaseBiz;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.util.EntityUtils;
import me.flyray.common.util.Query;
import me.flyray.common.util.SnowFlake;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 商户客户基础信息
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:49
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MerchantBaseBiz extends BaseBiz<MerchantBaseMapper, MerchantBase> {
	@Autowired
	private PlatformBaseBiz platformBaseBiz;
	@Autowired
	private FeignAdminClient feignAdminClient;
	@Autowired
	private CustomerBaseMapper customerBaseMapper;
	@Autowired
	private MerchantBaseExtMapper extMapper;
	/**
	 * 查询商户基础信息列表
	 * @author centerroot
	 * @time 创建时间:2018年7月20日上午11:32:40
	 * @param queryPersonalBaseListRequest
	 * @return
	 */
	public Map<String, Object> queryList(QueryMerchantBaseListRequest queryMerchantBaseListRequest){
		log.info("【查询商户基础信息列表】   请求参数：{}",EntityUtils.beanToMap(queryMerchantBaseListRequest));
		Map<String, Object> respMap = new HashMap<String, Object>();
		String platformId = queryMerchantBaseListRequest.getPlatformId();
		String merchantId = queryMerchantBaseListRequest.getMerchantId();
		String authenticationStatus = queryMerchantBaseListRequest.getAuthenticationStatus();
		String status = queryMerchantBaseListRequest.getStatus();
		String merType = queryMerchantBaseListRequest.getMerType();
		
		int page = queryMerchantBaseListRequest.getPage();
		int limit = queryMerchantBaseListRequest.getLimit();
		Map<String, Object> params = new HashMap<String, Object>();
	    params.put("page", page);
	    params.put("limit", limit);
	    Query query = new Query(params);
	    Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
		
		Example example = new Example(MerchantBase.class);
        Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(platformId)) {
        	criteria.andEqualTo("platformId", platformId);
		}
        if (!StringUtils.isEmpty(merchantId)) {
        	criteria.andEqualTo("merchantId", merchantId);
		}
        if (!StringUtils.isEmpty(authenticationStatus)) {
        	criteria.andEqualTo("authenticationStatus", authenticationStatus);
		}
        if (!StringUtils.isEmpty(status)) {
        	criteria.andEqualTo("status", status);
		}
        if (!StringUtils.isEmpty(merType)) {
        	criteria.andEqualTo("merType", merType);
        }
		example.setOrderByClause("create_time desc");
        List<MerchantBase> list = mapper.selectByExample(example);
        
        TableResultResponse<MerchantBase> table = new TableResultResponse<MerchantBase>(result.getTotal(), list);
        respMap.put("body", table);
        respMap.put("code", ResponseCode.OK.getCode());
        respMap.put("message", ResponseCode.OK.getMessage());
		log.info("【查询商户基础信息列表】   响应参数：{}",respMap);
		return respMap;
	}
	
	
	/**
	 * 小程序查询运营人员下面的商户
	 * @param param
	 * @return
	 */
	public List<MerchantBase> queryList(QueryMerchantListParam param){
		String platformId = param.getPlatformId();
		String operatorId = param.getOperatorId();
		Example example = new Example(MerchantBase.class);
        Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(platformId)) {
        	criteria.andEqualTo("platformId", platformId);
		}
        if (!StringUtils.isEmpty(operatorId)) {
        	criteria.andEqualTo("owner", Long.valueOf(operatorId));
		}
        List<MerchantBase> list = mapper.selectByExample(example);
		return list;
	}
	
	/**
	 * 添加商户基础信息
	 * @author centerroot
	 * @time 创建时间:2018年7月16日下午6:02:15
	 * @param MerchantBaseRequest
	 * @return
	 */
	public Map<String, Object> add(MerchantBaseRequest merchantBaseRequest){
		log.info("【添加商户基础信息】   请求参数：{}",EntityUtils.beanToMap(merchantBaseRequest));
		Map<String, Object> respMap = new HashMap<String, Object>();
		MerchantBase reqMerchantBase = new MerchantBase();
		reqMerchantBase.setMerchantName(merchantBaseRequest.getMerchantName());
		List<MerchantBase> respMerchants = mapper.select(reqMerchantBase);
		if (null != respMerchants && respMerchants.size() > 0) {
			respMap.put("code", ResponseCode.MER_LOGIN_NAME_EXIST.getCode());
			respMap.put("message", ResponseCode.MER_LOGIN_NAME_EXIST.getMessage());
		}else{
			Map<String, Object> reqMap = new HashMap<String, Object>();
			reqMap.put("mobilePhone", merchantBaseRequest.getMobilePhone());
			if(StringUtils.isEmpty(merchantBaseRequest.getMobilePhone())){
				respMap.put("code", ResponseCode.OK.getCode());
			}else{
				respMap = feignAdminClient.queryByMobile(reqMap);
			}
			if(ResponseCode.OK.getCode().equals(respMap.get("code")) && null == respMap.get("info")){
				MerchantBase merchantBase = new MerchantBase();
				BeanUtils.copyProperties(merchantBaseRequest,merchantBase);
				String merchantId = String.valueOf(SnowFlake.getId());
				String customerId = String.valueOf(SnowFlake.getId());
				merchantBase.setMerchantId(merchantId);
				merchantBase.setAuthenticationStatus("00");
				merchantBase.setStatus("00");
				merchantBase.setCustomerId(customerId);
				//写入商户基础信息
				mapper.insert(merchantBase);
				//写入一条客户信息
				CustomerBase customerBase = new CustomerBase();
				customerBase.setCreateTime(new Date());
				customerBase.setCustomerId(customerId);
				customerBase.setMerchantId(merchantId);
				customerBase.setCustomerType("CUST01");
				customerBase.setPlatformId(merchantBaseRequest.getPlatformId());
				customerBaseMapper.insert(customerBase);
				//写入商户扩展信息
				MerchantBaseExt merchantBaseExt = new MerchantBaseExt();
				merchantBaseExt.setMerchantId(merchantId);
				merchantBaseExt.setSigningDate(new Date());
				merchantBaseExt.setCreateTime(new Date());
				merchantBaseExt.setProvince(merchantBaseRequest.getProvince());
				merchantBaseExt.setCity(merchantBaseRequest.getCity());
				merchantBaseExt.setCounty(merchantBaseRequest.getCounty());
				merchantBaseExt.setSocialSecuritySpecialNo(merchantBaseRequest.getSocialSecuritySpecialNo());
				extMapper.insert(merchantBaseExt);
				
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("merchantName", merchantBase.getMerchantName());
				map.put("merchantId", merchantId);
				map.put("platformId", merchantBase.getPlatformId());
				map.put("token", merchantBaseRequest.getToken());
				map.put("type", 3);
				map.put("mobilePhone", merchantBaseRequest.getMobilePhone());
				//platformBaseBiz.commonAdd(map);
				Map<String,Object> reMap = feignAdminClient.addPlatformOrMerchant(map);
				
				String code = (String) reMap.get("code");
				if(ResponseCode.OK.getCode().equals(code)){
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("message", ResponseCode.OK.getMessage());
				}else {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					respMap.put("code", reMap.get("code"));
					respMap.put("message", reMap.get("msg"));
				}
			}else{
				respMap.put("code", ResponseCode.MOBILE_REPEAT.getCode());
				respMap.put("message", ResponseCode.MOBILE_REPEAT.getMessage());
			}
		}
		log.info("【添加商户基础信息】   响应参数：{}",respMap);
		return respMap;
	}
	/**
	 * 查询单个
	 */
	public MerchantBase queryInfo(String merchantId){
		MerchantBase merchantBase = new MerchantBase();
		merchantBase.setMerchantId(merchantId);
		List<MerchantBase> list = mapper.select(merchantBase);
		if(list.size() > 0){
			merchantBase = list.get(0);
			return merchantBase;
		}else {
			return null;
		}
	}
	
	
	/**
	 * 根据序号删除商户基础信息
	 * @author centerroot
	 * @time 创建时间:2018年8月24日下午2:50:55
	 * @param id
	 * @return
	 */
	public Map<String, Object> deleteOne(Integer id){
		log.info("【根据序号删除商户基础信息】   请求参数：id:{}",id);
		Map<String, Object> respMap = new HashMap<String, Object>();
		MerchantBase merchantBase = mapper.selectByPrimaryKey(id);

		log.info("【根据序号删除商户基础信息】   merchantBase：{}",EntityUtils.beanToMap(merchantBase));
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("platformId", merchantBase.getPlatformId());
		reqMap.put("merchantId", merchantBase.getMerchantId());
		reqMap.put("merchantName", merchantBase.getMerchantName());
		reqMap.put("type", 3);
		respMap = feignAdminClient.deletePlatformOrMerchant(reqMap);
		mapper.deleteByPrimaryKey(id);
		
		log.info("【根据序号删除商户基础信息】   响应参数：{}",respMap);
		return respMap;
	}
	
	/**
	 * 查询商户主表信息
	 * @param request
	 * @return
	 */
	public MerchantBase queryMerchantBaseInfo(Map<String, Object> request){
		MerchantBase merchantBase = new MerchantBase();
		merchantBase.setPlatformId((String) request.get("platformId"));
		merchantBase.setMerchantId((String) request.get("merchantId"));
		MerchantBase selectMerchantBase = mapper.selectOne(merchantBase);
		return selectMerchantBase;
	}
	
	/**
	 * 查询商户交易密码
	 * @param request
	 * @return
	 */
	public CustomerBase queryMerchantPassword(Map<String, Object> request){
		log.info("【查询商户交易密码】   请求参数{}",request);
		MerchantBase merchantBase = new MerchantBase();
		merchantBase.setPlatformId((String) request.get("platformId"));
		merchantBase.setMerchantId((String) request.get("merchantId"));
		MerchantBase selectMerchantBase = mapper.selectOne(merchantBase);
		CustomerBase selectCustomerBase = null;
		if(null != selectMerchantBase){
			String customerId = selectMerchantBase.getCustomerId();
			CustomerBase customerBase = new CustomerBase();
			customerBase.setPlatformId((String) request.get("platformId"));
			customerBase.setCustomerId(customerId);
			selectCustomerBase = customerBaseMapper.selectOne(customerBase);
		}
		log.info("【查询商户交易密码】   响应参数{}",EntityUtils.beanToMap(selectCustomerBase));
		return selectCustomerBase;
	}
	
	/**
	 * 查询商户信息
	 * @param request
	 * @return
	 */
	public Map<String, Object> queryMerchantInfo(Map<String, Object> request){		
		log.info("【查询商户信息】   请求参数：{}",request);
		Map<String, Object> respMap = new HashMap<String, Object>();
		MerchantBase merchantBaseQuery = new MerchantBase();
		merchantBaseQuery.setPlatformId((String) request.get("platformId"));
		merchantBaseQuery.setMerchantId((String) request.get("merchantId"));
		MerchantBase merchantBase = mapper.selectOne(merchantBaseQuery);
		if(merchantBase!=null){
			respMap.put("merchantBase", merchantBase);
			MerchantBaseExt merchantBaseExtQuery = new MerchantBaseExt();
			merchantBaseExtQuery.setMerchantId((String) request.get("merchantId"));
			MerchantBaseExt merchantBaseExt=extMapper.selectOne(merchantBaseExtQuery);
			if(merchantBaseExt!=null){
				respMap.put("merchantBaseExt", merchantBaseExt);
			}
			
			respMap.put("code", ResponseCode.OK.getCode());
	        respMap.put("msg", ResponseCode.OK.getMessage());
		} else {
			respMap.put("code", ResponseCode.MER_NOTEXIST.getCode());
	        respMap.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
		}
		log.info("【查询商户信息】   响应参数：{}",respMap);
		return respMap;
	}
	
}